"""
智能车联网统一多域标识认证安全管理系统 - GUI完整实现
基于PySide6开发，包含核心功能模块和零信任安全特性
"""

import sys
from PySide6.QtCore import Qt, QThread, Signal, QTimer
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QStackedWidget,
                               QListWidget, QVBoxLayout, QHBoxLayout, QLabel,
                               QLineEdit, QPushButton, QTableWidget, QTextEdit,
                               QComboBox, QMessageBox, QDateEdit, QProgressBar,
                               QTableWidgetItem,QCheckBox, QSpinBox)  # Add QTableWidgetItem to imports
from PySide6.QtGui import QFont,QIcon
from gmssl import sm2, sm3, sm4
import random
import csv
import json
import pandas as pd
from datetime import datetime, timedelta
import os

# ----------------- 后端模拟逻辑（实际需替换为业务实现）-----------------
# 在Backend类中添加以下业务逻辑方法
class Backend:
    @staticmethod
    def cross_domain_auth(source, target):
        """模拟跨域认证逻辑"""
        return True if len(source) > 0 and len(target) > 0 else False

    @staticmethod
    def generate_umi(domain, entity):
        """生成统一多域标识(基于SM3哈希算法)"""
        data = f"{domain}:{entity}".encode('utf-8')
        # Convert bytes to list of integers
        msg = list(data)
        msg.append(0x80)  # Padding start marker
        # Pad with zeros until length meets requirement
        while len(msg) % 64 != 56:
            msg.append(0)
        # Add length info (big-endian, 64-bit)
        msg += [0] * 8
        length = len(data) * 8
        msg[-8:] = [
            (length >> 56) & 0xff,
            (length >> 48) & 0xff,
            (length >> 40) & 0xff,
            (length >> 32) & 0xff,
            (length >> 24) & 0xff,
            (length >> 16) & 0xff,
            (length >> 8) & 0xff,
            length & 0xff
        ]
        # Call sm3_hash with proper input format
        hash_hex = sm3.sm3_hash(msg)
        return hash_hex[:16]  # Take first 16 chars as UMI

    @staticmethod
    def verify_umi(umi):
        """验证UMI标识的有效性"""
        return len(umi) == 16 and all(c in '0123456789abcdef' for c in umi)

    @staticmethod
    def get_domain_policies(domain):
        """获取指定域的安全策略"""
        policies = {
            "车企A": {"auth_level": 2, "data_encrypt": True},
            "车企B": {"auth_level": 2, "data_encrypt": True},
            "区域1": {"auth_level": 1, "data_encrypt": False},
            "区域2": {"auth_level": 1, "data_encrypt": False},
            "云平台": {"auth_level": 3, "data_encrypt": True}
        }
        return policies.get(domain, {})

    @staticmethod
    def encrypt_data(data, domain):
        """域数据加密"""
        if Backend.get_domain_policies(domain).get("data_encrypt"):
            # 使用SM4加密
            key = sm4.sm4_key()[:16].encode()
            crypt_sm4 = sm4.CryptSM4()
            crypt_sm4.set_key(key, sm4.SM4_ENCRYPT)
            return crypt_sm4.crypt_ecb(data.encode())
        return data.encode()

    @staticmethod
    def get_auth_policies():
        """获取所有认证策略"""
        return [
            {"source": "车企A", "target": "车企B", "allowed": True},
            {"source": "车企A", "target": "云平台", "allowed": True},
            {"source": "车企B", "target": "云平台", "allowed": True},
            {"source": "区域1", "target": "车企A", "allowed": False},
            {"source": "区域2", "target": "车企B", "allowed": True},
            {"source": "云平台", "target": "区域1", "allowed": True},
            {"source": "云平台", "target": "区域2", "allowed": True},
            {"source": "车企A", "target": "区域1", "allowed": False},
            {"source": "车企B", "target": "区域2", "allowed": True},
            {"source": "区域1", "target": "区域2", "allowed": True}
        ]

    @staticmethod
    def evaluate_risk_score(entity, action):
        """评估实体行为的风险分数"""
        risk_factors = {
            "认证失败": 0.8,
            "异常访问": 0.6,
            "数据泄露": 0.9,
            "权限提升": 0.7
        }
        base_score = risk_factors.get(action, 0.5)
        return base_score

    @staticmethod
    def apply_zero_trust_policy(policy_id, entity, action):
        """应用零信任策略"""
        policies = {
            "POL-001": {"type": "访问控制", "level": "高"},
            "POL-002": {"type": "数据加密", "level": "严格"},
            "POL-003": {"type": "行为监控", "level": "中"},
            "POL-004": {"type": "风险评估", "level": "高"}
        }
        
        policy = policies.get(policy_id, {})
        if not policy:
            return False
            
        risk_score = Backend.evaluate_risk_score(entity, action)
        
        # 根据策略级别调整风险阈值
        level_thresholds = {
            "低": 0.8,
            "中": 0.6,
            "高": 0.4,
            "严格": 0.2
        }
        
        threshold = level_thresholds.get(policy["level"], 0.5)
        return risk_score <= threshold

    @staticmethod
    def monitor_behavior(entity, action):
        """监控实体行为"""
        risk_score = Backend.evaluate_risk_score(entity, action)
        if risk_score > 0.7:
            return {
                "status": "高风险",
                "action": "阻断访问",
                "score": risk_score
            }
        elif risk_score > 0.5:
            return {
                "status": "中风险",
                "action": "增强认证",
                "score": risk_score
            }
        else:
            return {
                "status": "低风险",
                "action": "正常访问",
                "score": risk_score
            }

    @staticmethod
    def dynamic_access_control(entity, resource, action):
        """动态访问控制"""
        # 获取实体的历史行为
        history = {
            "认证失败": 0,
            "异常访问": 0,
            "数据泄露": 0,
            "权限提升": 0
        }
        
        # 计算综合风险分数
        total_risk = sum(history.values()) / len(history)
        
        # 根据风险等级调整访问权限
        if total_risk > 0.7:
            return False
        elif total_risk > 0.5:
            return True  # 需要额外认证
        else:
            return True  # 允许访问

class KeyManagerUI(QWidget):
    """密钥管理模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 密钥生成区域
        key_gen_layout = QHBoxLayout()
        self.key_type = QComboBox()
        self.key_type.addItems(["SM2", "SM4"])
        self.key_length = QComboBox()
        self.key_length.addItems(["128位", "192位", "256位"])
        gen_btn = QPushButton("生成密钥", clicked=self.generate_key)
        
        key_gen_layout.addWidget(QLabel("算法类型:"))
        key_gen_layout.addWidget(self.key_type)
        key_gen_layout.addWidget(QLabel("密钥长度:"))
        key_gen_layout.addWidget(self.key_length)
        key_gen_layout.addWidget(gen_btn)
        
        # 密钥显示区域
        self.key_display = QTextEdit(readOnly=True)
        self.key_display.setFont(QFont("Consolas", 10))
        
        # 密钥操作按钮
        btn_layout = QHBoxLayout()
        save_btn = QPushButton("保存密钥")
        load_btn = QPushButton("加载密钥")
        export_btn = QPushButton("导出证书")
        
        btn_layout.addWidget(save_btn)
        btn_layout.addWidget(load_btn)
        btn_layout.addWidget(export_btn)
        
        # 密钥列表
        self.key_table = QTableWidget(0, 4)
        self.key_table.setHorizontalHeaderLabels(["ID", "类型", "长度", "创建时间"])
        
        layout.addLayout(key_gen_layout)
        layout.addWidget(self.key_display)
        layout.addLayout(btn_layout)
        layout.addWidget(QLabel("密钥列表:"))
        layout.addWidget(self.key_table)
        self.setLayout(layout)
        
        # 加载示例数据
        self.load_demo_keys()

    def generate_key(self):
        """生成新密钥"""
        key_type = self.key_type.currentText()
        length = self.key_length.currentText()
        
        try:
            if key_type == "SM2":
                # SM2密钥生成
                private_key = os.urandom(32)  # 生成32字节随机私钥
                public_key = os.urandom(64)   # 生成64字节随机公钥
                crypt_sm2 = sm2.CryptSM2(private_key=private_key, public_key=public_key)
                key_info = f"私钥: {private_key.hex()}\n公钥: {public_key.hex()}"
            else:  # SM4
                # SM4密钥生成
                key = os.urandom(16)  # 生成16字节随机密钥
                crypt_sm4 = sm4.CryptSM4()
                crypt_sm4.set_key(key, sm4.SM4_ENCRYPT)
                key_info = f"密钥: {key.hex()}"
                
            self.key_display.setPlainText(f"{key_type}密钥({length}):\n{key_info}")
            self.add_key_to_table(key_type, length, key_info)
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"密钥生成失败: {str(e)}")

    def add_key_to_table(self, key_type, length, key_info):
        """添加密钥到表格"""
        row = self.key_table.rowCount()
        self.key_table.insertRow(row)
        self.key_table.setItem(row, 0, QTableWidgetItem(f"KEY-{row+1:03d}"))
        self.key_table.setItem(row, 1, QTableWidgetItem(key_type))
        self.key_table.setItem(row, 2, QTableWidgetItem(length))
        self.key_table.setItem(row, 3, QTableWidgetItem(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    def load_demo_keys(self):
        """加载示例密钥数据"""
        demo_keys = [
            {"id": "KEY-001", "type": "SM2", "length": "256位", "time": "2023-11-01"},
            {"id": "KEY-002", "type": "SM4", "length": "128位", "time": "2023-11-05"},
            {"id": "KEY-003", "type": "SM2", "length": "256位", "time": "2023-11-10"}
        ]
        
        for key in demo_keys:
            row = self.key_table.rowCount()
            self.key_table.insertRow(row)
            self.key_table.setItem(row, 0, QTableWidgetItem(key["id"]))
            self.key_table.setItem(row, 1, QTableWidgetItem(key["type"]))
            self.key_table.setItem(row, 2, QTableWidgetItem(key["length"]))
            self.key_table.setItem(row, 3, QTableWidgetItem(key["time"]))


class SecureCommUI(QWidget):
    """安全通信模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 通信设置区域
        setting_layout = QHBoxLayout()
        self.protocol = QComboBox()
        self.protocol.addItems(["SM2+SM3", "SM4", "TLS 1.3"])
        self.encrypt_check = QCheckBox("启用加密")
        self.encrypt_check.setChecked(True)
        
        setting_layout.addWidget(QLabel("安全协议:"))
        setting_layout.addWidget(self.protocol)
        setting_layout.addWidget(self.encrypt_check)
        
        # 消息区域
        msg_layout = QHBoxLayout()
        self.msg_input = QTextEdit()
        self.msg_input.setPlaceholderText("输入要发送的消息...")
        self.msg_history = QTextEdit(readOnly=True)
        
        msg_layout.addWidget(self.msg_input)
        msg_layout.addWidget(self.msg_history)
        
        # 操作按钮
        btn_layout = QHBoxLayout()
        send_btn = QPushButton("发送", clicked=self.send_message)
        clear_btn = QPushButton("清空")
        
        btn_layout.addWidget(send_btn)
        btn_layout.addWidget(clear_btn)
        
        # 状态显示
        self.status = QLabel("准备就绪")
        self.status.setAlignment(Qt.AlignCenter)
        
        layout.addLayout(setting_layout)
        layout.addLayout(msg_layout)
        layout.addLayout(btn_layout)
        layout.addWidget(self.status)
        self.setLayout(layout)
        
        # 加载示例消息
        self.load_demo_messages()

    def send_message(self):
        """发送安全消息"""
        msg = self.msg_input.toPlainText()
        if not msg:
            QMessageBox.warning(self, "错误", "消息内容不能为空")
            return
            
        protocol = self.protocol.currentText()
        encrypted = self.encrypt_check.isChecked()
        
        try:
            # 模拟加密过程
            if encrypted:
                encrypted_msg = f"[加密]{msg}"
            else:
                encrypted_msg = msg
                
            # 添加到历史记录
            self.msg_history.append(f"[{protocol}] {encrypted_msg}")
            self.msg_input.clear()
            self.status.setText("消息发送成功")
            
        except Exception as e:
            self.status.setText(f"发送失败: {str(e)}")

    def load_demo_messages(self):
        """加载示例消息"""
        demo_msgs = [
            "[SM2+SM3] [加密]系统初始化完成",
            "[SM4] [加密]密钥交换成功",
            "[TLS 1.3] 安全通道已建立"
        ]
        
        for msg in demo_msgs:
            self.msg_history.append(msg)

# ----------------- 多线程任务类 -----------------
class AuthWorker(QThread):
    auth_result = Signal(bool)
    log_signal = Signal(str)
    progress_updated = Signal(int)
    
    def __init__(self, source, target):
        super().__init__()
        self.source = source
        self.target = target
        
    def run(self):
        try:
            self.log_signal.emit(f"开始认证: {self.source} → {self.target}")
            
            # 模拟认证过程
            for i in range(1, 101):
                self.msleep(50)  # 模拟耗时操作
                self.progress_updated.emit(i)
                
                if i % 20 == 0:
                    self.log_signal.emit(f"认证进度: {i}%")
                    
            result = Backend.cross_domain_auth(self.source, self.target)
            self.auth_result.emit(result)
            
        except Exception as e:
            self.log_signal.emit(f"认证错误: {str(e)}")
            self.auth_result.emit(False)

# ----------------- 各功能模块UI组件 -----------------
class IdentifierUI(QWidget):
    """统一标识管理模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 初始化数据
        self.identifiers = []
        self.data_counter = 0  # 添加数据计数器初始化
        
        # 输入区域
        input_layout = QHBoxLayout()
        self.domain_input = QLineEdit(placeholderText="输入域ID")
        self.entity_input = QLineEdit(placeholderText="输入实体ID")
        gen_btn = QPushButton("生成UMI", clicked=self.generate_umi)
        input_layout.addWidget(QLabel("域ID:"))
        input_layout.addWidget(self.domain_input)
        input_layout.addWidget(QLabel("实体ID:"))
        input_layout.addWidget(self.entity_input)
        input_layout.addWidget(gen_btn)
        
        # 显示区域
        self.umi_table = QTableWidget(0, 4)
        self.umi_table.setHorizontalHeaderLabels(["域ID", "实体ID", "UMI", "更新时间"])
        
        # 统计信息
        self.stats_text = QTextEdit(readOnly=True)
        self.stats_text.setMaximumHeight(100)
        
        # 控制区域
        control_layout = QHBoxLayout()
        self.auto_update = QCheckBox("自动更新")
        self.auto_update.setChecked(True)
        self.update_interval = QSpinBox()
        self.update_interval.setRange(1, 60)
        self.update_interval.setValue(20)
        self.update_interval.setSuffix(" 秒")
        self.update_interval.valueChanged.connect(self.update_timer_interval)
        
        control_layout.addWidget(self.auto_update)
        control_layout.addWidget(QLabel("更新间隔:"))
        control_layout.addWidget(self.update_interval)
        
        layout.addLayout(input_layout)
        layout.addLayout(control_layout)
        layout.addWidget(QLabel("标识列表:"))
        layout.addWidget(self.umi_table)
        layout.addWidget(QLabel("统计信息:"))
        layout.addWidget(self.stats_text)

        control_layout.addWidget(QPushButton("批量导入", clicked=self.batch_import))
        control_layout.addWidget(QPushButton("导出选中", clicked=self.export_selected))


        self.setLayout(layout)
        
        # 生成初始数据
        self.generate_demo_data()
        
        # 设置定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_data)
        self.timer.start(1000)  # 每秒更新一次

    def batch_import(self):
        """批量导入标识"""
        # 实现CSV/Excel文件导入逻辑
        pass

    def export_selected(self):
        """导出选中记录"""
        pass

    def renew_selected(self):
        """续期选中标识"""
        for row in set(index.row() for index in self.umi_table.selectedIndexes()):
            identifier = self.identifiers[row]
            identifier["expire_time"] = datetime.now() + timedelta(days=365)
            identifier["update_time"] = datetime.now()
        self.update_table()

    def update_timer_interval(self):
        """更新定时器间隔"""
        if self.auto_update.isChecked():
            self.timer.setInterval(self.update_interval.value() * 1000)
            
    def update_data(self):
        """更新数据"""
        if not self.auto_update.isChecked():
            return
            
        # 每秒生成20组数据
        for _ in range(20):
            self.generate_random_identifier()
            self.data_counter += 1
            
        # 更新显示
        self.update_table()
        self.update_stats()
        
    def generate_random_identifier(self):
        """生成随机标识数据"""
        domains = ["车企A", "车企B", "区域1", "区域2", "云平台", "交通中心"]
        entity_types = {
            "车企": ["车载终端", "诊断设备", "ECU模块"],
            "区域": ["信号灯", "摄像头", "雷达"],
            "云平台": ["计算节点", "存储节点", "API网关"],
            "交通中心": ["控制服务器", "数据分析", "监控终端"]
        }
        
        domain = random.choice(domains)
        prefix = domain[:2]
        entity_type = random.choice(entity_types.get(prefix, ["设备"]))
        entity_id = f"{entity_type}{random.randint(1000, 9999)}"
        
        umi = Backend.generate_umi(domain, entity_id)
        update_time = datetime.now()
        
        identifier = {
            "domain": domain,
            "entity": entity_id,
            "umi": umi,
            "update_time": update_time
        }
        
        self.identifiers.append(identifier)
        
        # 保持数据量在合理范围内
        if len(self.identifiers) > 1000:
            self.identifiers = self.identifiers[-1000:]
            
    def update_table(self):
        """更新表格时增加状态列"""
        self.umi_table.setHorizontalHeaderLabels(["域ID", "实体ID", "UMI", "状态", "有效期至", "更新时间"])

        """更新表格显示"""
        self.umi_table.setRowCount(0)
        for identifier in self.identifiers[-100:]:  # 只显示最近100条
            row = self.umi_table.rowCount()
            self.umi_table.insertRow(row)
            self.umi_table.setItem(row, 0, QTableWidgetItem(identifier["domain"]))
            self.umi_table.setItem(row, 1, QTableWidgetItem(identifier["entity"]))
            self.umi_table.setItem(row, 2, QTableWidgetItem(identifier["umi"]))
            self.umi_table.setItem(row, 3, QTableWidgetItem(
                identifier["update_time"].strftime("%Y-%m-%d %H:%M:%S")
            ))
            
    def update_stats(self):
        """更新统计信息"""
        total = len(self.identifiers)
        domain_stats = {}
        for identifier in self.identifiers:
            domain = identifier["domain"]
            domain_stats[domain] = domain_stats.get(domain, 0) + 1
            
        stats = f"""
统计信息:
总标识数: {total}
每秒生成: 20组
累计生成: {self.data_counter}组

各域分布:
"""
        for domain, count in domain_stats.items():
            stats += f"{domain}: {count} ({count/total*100:.1f}%)\n"
            
        self.stats_text.setPlainText(stats)
        
    def generate_umi(self):
        """手动生成UMI"""
        domain = self.domain_input.text()
        entity = self.entity_input.text()
        if not domain or not entity:
            QMessageBox.warning(self, "错误", "域ID和实体ID不能为空")
            return
            
        umi = Backend.generate_umi(domain, entity)
        update_time = datetime.now()
        
        identifier = {
            "domain": domain,
            "entity": entity,
            "umi": umi,
            "update_time": update_time
        }
        
        self.identifiers.append(identifier)
        self.update_table()
        self.update_stats()
        
        self.domain_input.clear()
        self.entity_input.clear()
        
    def generate_demo_data(self):
        """生成初始演示数据"""
        for _ in range(50):  # 初始生成50条数据
            self.generate_random_identifier()
        self.update_table()
        self.update_stats()

class AuthUI(QWidget):
    """跨域认证模块（包含多线程优化）"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 输入区域
        input_layout = QHBoxLayout()
        self.source_input = QComboBox()
        self.source_input.setEditable(True)
        self.source_input.setPlaceholderText("选择源域")
        
        self.target_input = QComboBox()
        self.target_input.setEditable(True)
        self.target_input.setPlaceholderText("选择目标域")
        
        # 添加域选项
        domains = ["车企A", "车企B", "区域1", "区域2", "云平台", "交通中心"]
        self.source_input.addItems(domains)
        self.target_input.addItems(domains)
        
        self.auth_btn = QPushButton("发起认证")
        self.auth_btn.clicked.connect(self.start_auth)
        
        input_layout.addWidget(QLabel("源域:"))
        input_layout.addWidget(self.source_input)
        input_layout.addWidget(QLabel("目标域:"))
        input_layout.addWidget(self.target_input)
        input_layout.addWidget(self.auth_btn)
        
        # 认证策略显示
        self.policy_table = QTableWidget(0, 3)
        self.policy_table.setHorizontalHeaderLabels(["源域", "目标域", "策略"])
        self.load_auth_policies()
        
        # 状态显示
        self.status_label = QLabel("准备就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setFont(QFont("Arial", 12, QFont.Bold))
        
        # 日志区域
        self.log_area = QTextEdit(readOnly=True)
        self.log_area.setFont(QFont("Consolas", 10))
        
        # 进度条
        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress.setValue(0)
        
        layout.addLayout(input_layout)
        layout.addWidget(QLabel("认证策略:"))
        layout.addWidget(self.policy_table)
        layout.addWidget(self.status_label)
        layout.addWidget(self.progress)
        layout.addWidget(QLabel("认证日志:"))
        layout.addWidget(self.log_area)
        self.setLayout(layout)

    def load_auth_policies(self):
        """加载认证策略到表格"""
        policies = Backend.get_auth_policies()  # 需要在后端添加此方法
        self.policy_table.setRowCount(0)
        for idx, policy in enumerate(policies):
            self.policy_table.insertRow(idx)
            self.policy_table.setItem(idx, 0, QTableWidgetItem(policy["source"]))
            self.policy_table.setItem(idx, 1, QTableWidgetItem(policy["target"]))
            status = "允许" if policy["allowed"] else "禁止"
            self.policy_table.setItem(idx, 2, QTableWidgetItem(status))
            
    def start_auth(self):
        source = self.source_input.currentText()
        target = self.target_input.currentText()
        
        if not source or not target:
            QMessageBox.warning(self, "错误", "必须选择源域和目标域")
            return
        
        # 检查是否允许认证
        if not self.check_auth_policy(source, target):
            QMessageBox.warning(self, "认证禁止", 
                              f"从 {source} 到 {target} 的认证被策略禁止")
            return
            
        self.auth_btn.setEnabled(False)
        self.status_label.setText("认证中...")
        self.status_label.setStyleSheet("color: blue;")
        self.progress.setValue(0)
        
        self.worker = AuthWorker(source, target)
        self.worker.auth_result.connect(self.handle_result)
        self.worker.log_signal.connect(self.log_area.append)
        self.worker.progress_updated.connect(self.progress.setValue)
        self.worker.finished.connect(lambda: self.auth_btn.setEnabled(True))
        self.worker.start()

    def check_auth_policy(self, source, target):
        """检查认证策略是否允许"""
        policies = Backend.get_auth_policies()
        return any(p["source"] == source and p["target"] == target and p["allowed"] 
                  for p in policies)

    def handle_result(self, success):
        if success:
            status = "认证成功"
            color = "green"
            self.progress.setValue(100)
        else:
            status = "认证失败" 
            color = "red"
            self.progress.setValue(0)
            
        self.status_label.setText(status)
        self.status_label.setStyleSheet(f"color: {color}; font-weight: bold;")
        self.log_area.append(f"{datetime.now().strftime('%H:%M:%S')} - {status}")

class ZeroTrustPolicyUI(QWidget):
    """零信任安全策略管理模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 策略配置区域
        policy_config = QHBoxLayout()
        self.policy_name = QLineEdit(placeholderText="策略名称")
        self.policy_type = QComboBox()
        self.policy_type.addItems(["访问控制", "数据加密", "行为监控", "风险评估"])
        self.policy_level = QComboBox()
        self.policy_level.addItems(["低", "中", "高", "严格"])
        add_btn = QPushButton("添加策略", clicked=self.add_policy)
        
        policy_config.addWidget(QLabel("策略名称:"))
        policy_config.addWidget(self.policy_name)
        policy_config.addWidget(QLabel("策略类型:"))
        policy_config.addWidget(self.policy_type)
        policy_config.addWidget(QLabel("安全级别:"))
        policy_config.addWidget(self.policy_level)
        policy_config.addWidget(add_btn)
        
        # 策略列表
        self.policy_table = QTableWidget(0, 4)
        self.policy_table.setHorizontalHeaderLabels(["策略ID", "策略名称", "策略类型", "安全级别"])
        
        # 策略详情
        self.policy_detail = QTextEdit(readOnly=True)
        self.policy_detail.setPlaceholderText("选择策略查看详情...")
        
        # 操作按钮
        btn_layout = QHBoxLayout()
        edit_btn = QPushButton("编辑策略")
        delete_btn = QPushButton("删除策略")
        export_btn = QPushButton("导出策略")
        
        btn_layout.addWidget(edit_btn)
        btn_layout.addWidget(delete_btn)
        btn_layout.addWidget(export_btn)
        
        layout.addLayout(policy_config)
        layout.addWidget(QLabel("策略列表:"))
        layout.addWidget(self.policy_table)
        layout.addWidget(QLabel("策略详情:"))
        layout.addWidget(self.policy_detail)
        layout.addLayout(btn_layout)
        
        self.setLayout(layout)
        self.load_demo_policies()
        
        # 连接信号
        self.policy_table.itemSelectionChanged.connect(self.show_policy_detail)
        
    def add_policy(self):
        """添加新的零信任策略"""
        name = self.policy_name.text()
        p_type = self.policy_type.currentText()
        level = self.policy_level.currentText()
        
        if not name:
            QMessageBox.warning(self, "错误", "策略名称不能为空")
            return
            
        row = self.policy_table.rowCount()
        self.policy_table.insertRow(row)
        self.policy_table.setItem(row, 0, QTableWidgetItem(f"POL-{row+1:03d}"))
        self.policy_table.setItem(row, 1, QTableWidgetItem(name))
        self.policy_table.setItem(row, 2, QTableWidgetItem(p_type))
        self.policy_table.setItem(row, 3, QTableWidgetItem(level))
        
        self.policy_name.clear()
        
    def show_policy_detail(self):
        """显示选中策略的详细信息"""
        selected = self.policy_table.selectedItems()
        if not selected:
            return
            
        policy_id = selected[0].text()
        policy_name = selected[1].text()
        policy_type = selected[2].text()
        policy_level = selected[3].text()
        
        detail = f"""
策略ID: {policy_id}
策略名称: {policy_name}
策略类型: {policy_type}
安全级别: {policy_level}

策略描述:
根据零信任安全模型，此策略将执行以下操作：
1. 持续验证身份和权限
2. 实施最小权限访问控制
3. 监控异常行为
4. 动态调整访问权限
"""
        self.policy_detail.setPlainText(detail)
        
    def load_demo_policies(self):
        """加载示例策略数据"""
        demo_policies = [
            {"id": "POL-001", "name": "车载终端访问控制", "type": "访问控制", "level": "高"},
            {"id": "POL-002", "name": "数据加密传输", "type": "数据加密", "level": "严格"},
            {"id": "POL-003", "name": "行为异常检测", "type": "行为监控", "level": "中"},
            {"id": "POL-004", "name": "风险评估策略", "type": "风险评估", "level": "高"}
        ]
        
        for policy in demo_policies:
            row = self.policy_table.rowCount()
            self.policy_table.insertRow(row)
            self.policy_table.setItem(row, 0, QTableWidgetItem(policy["id"]))
            self.policy_table.setItem(row, 1, QTableWidgetItem(policy["name"]))
            self.policy_table.setItem(row, 2, QTableWidgetItem(policy["type"]))
            self.policy_table.setItem(row, 3, QTableWidgetItem(policy["level"]))

class DataGeneratorUI(QWidget):
    """模拟数据生成模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 数据生成配置
        config_layout = QHBoxLayout()
        self.data_type = QComboBox()
        self.data_type.addItems(["认证日志", "行为数据", "风险评估", "策略执行"])
        self.data_count = QSpinBox()
        self.data_count.setRange(1, 1000)
        self.data_count.setValue(100)
        self.time_range = QComboBox()
        self.time_range.addItems(["最近1小时", "最近24小时", "最近7天", "最近30天"])
        generate_btn = QPushButton("生成数据", clicked=self.generate_data)
        
        config_layout.addWidget(QLabel("数据类型:"))
        config_layout.addWidget(self.data_type)
        config_layout.addWidget(QLabel("数据量:"))
        config_layout.addWidget(self.data_count)
        config_layout.addWidget(QLabel("时间范围:"))
        config_layout.addWidget(self.time_range)
        config_layout.addWidget(generate_btn)
        
        # 数据预览
        self.preview_table = QTableWidget(0, 5)
        self.preview_table.setHorizontalHeaderLabels(["时间", "实体ID", "操作类型", "风险等级", "状态"])
        
        # 数据导出
        export_layout = QHBoxLayout()
        self.export_format = QComboBox()
        self.export_format.addItems(["CSV", "JSON", "Excel"])
        export_btn = QPushButton("导出数据", clicked=self.export_data)
        
        export_layout.addWidget(QLabel("导出格式:"))
        export_layout.addWidget(self.export_format)
        export_layout.addWidget(export_btn)
        
        # 统计信息
        self.stats_text = QTextEdit(readOnly=True)
        self.stats_text.setMaximumHeight(100)
        
        layout.addLayout(config_layout)
        layout.addWidget(QLabel("数据预览:"))
        layout.addWidget(self.preview_table)
        layout.addLayout(export_layout)
        layout.addWidget(QLabel("统计信息:"))
        layout.addWidget(self.stats_text)
        
        self.setLayout(layout)
        self.generated_data = []
        
    def generate_data(self):
        """生成模拟数据"""
        data_type = self.data_type.currentText()
        count = self.data_count.value()
        time_range = self.time_range.currentText()
        
        self.generated_data = []
        self.preview_table.setRowCount(0)
        
        # 生成时间范围
        end_time = datetime.now()
        if time_range == "最近1小时":
            start_time = end_time - timedelta(hours=1)
        elif time_range == "最近24小时":
            start_time = end_time - timedelta(days=1)
        elif time_range == "最近7天":
            start_time = end_time - timedelta(days=7)
        else:
            start_time = end_time - timedelta(days=30)
            
        # 生成数据
        for i in range(count):
            time = start_time + (end_time - start_time) * random.random()
            entity_id = f"ENT-{random.randint(1000, 9999)}"
            action = random.choice(["登录", "访问", "修改", "删除", "创建"])
            risk_level = random.choice(["低", "中", "高"])
            status = random.choice(["成功", "失败", "警告"])
            
            data = {
                "time": time,
                "entity_id": entity_id,
                "action": action,
                "risk_level": risk_level,
                "status": status
            }
            self.generated_data.append(data)
            
            # 添加到预览表格
            row = self.preview_table.rowCount()
            self.preview_table.insertRow(row)
            self.preview_table.setItem(row, 0, QTableWidgetItem(time.strftime("%Y-%m-%d %H:%M:%S")))
            self.preview_table.setItem(row, 1, QTableWidgetItem(entity_id))
            self.preview_table.setItem(row, 2, QTableWidgetItem(action))
            self.preview_table.setItem(row, 3, QTableWidgetItem(risk_level))
            self.preview_table.setItem(row, 4, QTableWidgetItem(status))
            
        # 更新统计信息
        self.update_stats()
        
    def update_stats(self):
        """更新统计信息"""
        if not self.generated_data:
            return
            
        total = len(self.generated_data)
        success = sum(1 for d in self.generated_data if d["status"] == "成功")
        failed = sum(1 for d in self.generated_data if d["status"] == "失败")
        warning = sum(1 for d in self.generated_data if d["status"] == "警告")
        
        high_risk = sum(1 for d in self.generated_data if d["risk_level"] == "高")
        medium_risk = sum(1 for d in self.generated_data if d["risk_level"] == "中")
        low_risk = sum(1 for d in self.generated_data if d["risk_level"] == "低")
        
        stats = f"""
数据统计:
总记录数: {total}
成功操作: {success} ({success/total*100:.1f}%)
失败操作: {failed} ({failed/total*100:.1f}%)
警告操作: {warning} ({warning/total*100:.1f}%)

风险分布:
高风险: {high_risk} ({high_risk/total*100:.1f}%)
中风险: {medium_risk} ({medium_risk/total*100:.1f}%)
低风险: {low_risk} ({low_risk/total*100:.1f}%)
"""
        self.stats_text.setPlainText(stats)
        
    def export_data(self):
        """导出数据"""
        if not self.generated_data:
            QMessageBox.warning(self, "错误", "没有可导出的数据")
            return
            
        format = self.export_format.currentText()
        filename = f"security_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        
        if format == "CSV":
            filename += ".csv"
            with open(filename, 'w', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerow(["时间", "实体ID", "操作类型", "风险等级", "状态"])
                for data in self.generated_data:
                    writer.writerow([
                        data["time"].strftime("%Y-%m-%d %H:%M:%S"),
                        data["entity_id"],
                        data["action"],
                        data["risk_level"],
                        data["status"]
                    ])
        elif format == "JSON":
            filename += ".json"
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.generated_data, f, default=str, ensure_ascii=False, indent=2)
        else:  # Excel
            filename += ".xlsx"
            df = pd.DataFrame(self.generated_data)
            df.to_excel(filename, index=False)
            
        QMessageBox.information(self, "成功", f"数据已导出到 {filename}")

class DataValidatorUI(QWidget):
    """数据验证模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 验证配置
        config_layout = QHBoxLayout()
        self.validation_type = QComboBox()
        self.validation_type.addItems([
            "完整性验证", "一致性验证", "有效性验证", "合规性验证"
        ])
        self.data_source = QComboBox()
        self.data_source.addItems([
            "认证日志", "行为数据", "风险评估", "策略执行"
        ])
        validate_btn = QPushButton("开始验证", clicked=self.validate_data)
        validate_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #218838;
            }
        """)
        
        config_layout.addWidget(QLabel("验证类型:"))
        config_layout.addWidget(self.validation_type)
        config_layout.addWidget(QLabel("数据源:"))
        config_layout.addWidget(self.data_source)
        config_layout.addWidget(validate_btn)
        
        # 验证结果
        self.result_table = QTableWidget(0, 4)
        self.result_table.setHorizontalHeaderLabels(["验证项", "状态", "详细信息", "时间"])
        self.result_table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #ddd;
                border-radius: 4px;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: 1px solid #ddd;
                font-weight: bold;
            }
        """)
        
        # 统计信息
        self.stats_text = QTextEdit(readOnly=True)
        self.stats_text.setMaximumHeight(150)
        self.stats_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
            }
        """)
        
        # 导出按钮
        export_btn = QPushButton("导出验证报告", clicked=self.export_report)
        export_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #138496;
            }
        """)
        
        layout.addLayout(config_layout)
        layout.addWidget(QLabel("验证结果:"))
        layout.addWidget(self.result_table)
        layout.addWidget(QLabel("统计信息:"))
        layout.addWidget(self.stats_text)
        layout.addWidget(export_btn)
        
        self.setLayout(layout)
        self.validation_results = []
        
    def validate_data(self):
        """执行数据验证"""
        v_type = self.validation_type.currentText()
        source = self.data_source.currentText()
        
        self.validation_results = []
        self.result_table.setRowCount(0)
        
        # 验证项目定义
        validation_items = {
            "完整性验证": [
                "数据完整性检查",
                "时间戳连续性",
                "必填字段检查",
                "数据格式验证"
            ],
            "一致性验证": [
                "跨域数据一致性",
                "时间序列一致性",
                "业务规则一致性",
                "状态转换一致性"
            ],
            "有效性验证": [
                "数据有效性检查",
                "业务规则验证",
                "权限有效性验证",
                "操作有效性验证"
            ],
            "合规性验证": [
                "安全策略合规性",
                "数据保护合规性",
                "访问控制合规性",
                "审计日志合规性"
            ]
        }
        
        items = validation_items.get(v_type, [])
        for item in items:
            # 模拟验证过程
            status = random.choices(["通过", "警告", "失败"], weights=[0.7, 0.2, 0.1])[0]
            details = self.generate_validation_details(item, status)
            time = datetime.now()
            
            result = {
                "item": item,
                "status": status,
                "details": details,
                "time": time
            }
            self.validation_results.append(result)
            
            # 添加到结果表格
            row = self.result_table.rowCount()
            self.result_table.insertRow(row)
            self.result_table.setItem(row, 0, QTableWidgetItem(item))
            
            # 设置状态颜色
            status_item = QTableWidgetItem(status)
            if status == "通过":
                status_item.setForeground(Qt.green)
            elif status == "警告":
                status_item.setForeground(Qt.orange)
            else:
                status_item.setForeground(Qt.red)
            self.result_table.setItem(row, 1, status_item)
            
            self.result_table.setItem(row, 2, QTableWidgetItem(details))
            self.result_table.setItem(row, 3, QTableWidgetItem(time.strftime("%Y-%m-%d %H:%M:%S")))
            
        # 更新统计信息
        self.update_stats()
        
    def generate_validation_details(self, item, status):
        """生成验证详情"""
        if status == "通过":
            return f"{item}验证通过，数据符合要求"
        elif status == "警告":
            warnings = [
                f"{item}存在潜在风险，建议进行数据清理",
                f"{item}部分数据异常，需要进一步检查",
                f"{item}存在数据不一致，建议进行数据同步",
                f"{item}部分记录不符合规范，需要修正"
            ]
            return random.choice(warnings)
        else:
            errors = [
                f"{item}验证失败，数据完整性受损",
                f"{item}违反业务规则，需要立即处理",
                f"{item}权限验证失败，请检查访问权限",
                f"{item}安全策略违规，需要及时修复"
            ]
            return random.choice(errors)
            
    def update_stats(self):
        """更新统计信息"""
        if not self.validation_results:
            return
            
        total = len(self.validation_results)
        passed = sum(1 for r in self.validation_results if r["status"] == "通过")
        warning = sum(1 for r in self.validation_results if r["status"] == "警告")
        failed = sum(1 for r in self.validation_results if r["status"] == "失败")
        
        # 按验证类型统计
        validation_stats = {}
        for r in self.validation_results:
            item = r["item"]
            if item not in validation_stats:
                validation_stats[item] = {"total": 0, "passed": 0}
            validation_stats[item]["total"] += 1
            if r["status"] == "通过":
                validation_stats[item]["passed"] += 1
        
        stats = f"""
验证统计:
总验证项: {total}
通过: {passed} ({passed/total*100:.1f}%)
警告: {warning} ({warning/total*100:.1f}%)
失败: {failed} ({failed/total*100:.1f}%)

各验证项通过率:
"""
        for item, data in validation_stats.items():
            pass_rate = data["passed"] / data["total"] * 100
            stats += f"{item}: {data['passed']}/{data['total']} ({pass_rate:.1f}%)\n"
            
        self.stats_text.setPlainText(stats)
        
    def export_report(self):
        """导出验证报告"""
        if not self.validation_results:
            QMessageBox.warning(self, "错误", "没有可导出的验证结果")
            return
            
        filename = f"validation_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
        
        # 生成HTML报告
        html = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>数据验证报告</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
                .passed { color: green; }
                .warning { color: orange; }
                .failed { color: red; }
            </style>
        </head>
        <body>
            <h1>数据验证报告</h1>
            <p>生成时间: {time}</p>
            <h2>验证结果</h2>
            <table>
                <tr>
                    <th>验证项</th>
                    <th>状态</th>
                    <th>详细信息</th>
                    <th>时间</th>
                </tr>
        """
        
        for result in self.validation_results:
            status_class = result["status"].lower()
            html += f"""
                <tr>
                    <td>{result['item']}</td>
                    <td class="{status_class}">{result['status']}</td>
                    <td>{result['details']}</td>
                    <td>{result['time'].strftime('%Y-%m-%d %H:%M:%S')}</td>
                </tr>
            """
            
        html += """
            </table>
            <h2>统计信息</h2>
            <pre>{stats}</pre>
        </body>
        </html>
        """
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(html.format(
                time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                stats=self.stats_text.toPlainText()
            ))
            
        QMessageBox.information(self, "成功", f"验证报告已导出到 {filename}")

class SecurityDefenseUI(QWidget):
    """安全防御模块"""
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        
        # 攻击类型选择
        attack_layout = QHBoxLayout()
        self.attack_type = QComboBox()
        self.attack_type.addItems([
            "DDoS攻击", "中间人攻击", "重放攻击", 
            "SQL注入", "XSS攻击", "权限提升"
        ])
        self.attack_type.currentTextChanged.connect(self.update_defense_info)
        
        # 攻击参数设置
        self.attack_params = QComboBox()
        self.attack_params.addItems(["低强度", "中强度", "高强度"])
        
        attack_layout.addWidget(QLabel("攻击类型:"))
        attack_layout.addWidget(self.attack_type)
        attack_layout.addWidget(QLabel("攻击强度:"))
        attack_layout.addWidget(self.attack_params)
        
        # 防御策略显示
        self.defense_info = QTextEdit(readOnly=True)
        self.defense_info.setFont(QFont("Consolas", 10))
        
        # 模拟攻击按钮
        simulate_btn = QPushButton("模拟攻击", clicked=self.simulate_attack)
        simulate_btn.setStyleSheet("""
            QPushButton {
                background-color: #dc3545;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c82333;
            }
        """)
        
        # 防御效果显示
        self.defense_result = QTableWidget(0, 5)
        self.defense_result.setHorizontalHeaderLabels(["时间", "攻击类型", "攻击强度", "防御措施", "结果"])
        self.defense_result.setStyleSheet("""
            QTableWidget {
                border: 1px solid #ddd;
                border-radius: 4px;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: 1px solid #ddd;
                font-weight: bold;
            }
        """)
        
        # 统计信息
        self.stats_text = QTextEdit(readOnly=True)
        self.stats_text.setMaximumHeight(150)
        self.stats_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
            }
        """)
        
        # 防御措施选择
        defense_layout = QHBoxLayout()
        self.defense_measures = QComboBox()
        self.defense_measures.addItems(["自动选择", "手动选择"])
        self.defense_measures.currentTextChanged.connect(self.toggle_defense_selection)
        
        self.defense_checkboxes = []
        for i in range(3):
            checkbox = QCheckBox(f"防御措施 {i+1}")
            checkbox.setVisible(False)
            self.defense_checkboxes.append(checkbox)
        
        defense_layout.addWidget(QLabel("防御方式:"))
        defense_layout.addWidget(self.defense_measures)
        for checkbox in self.defense_checkboxes:
            defense_layout.addWidget(checkbox)
        
        layout.addLayout(attack_layout)
        layout.addLayout(defense_layout)
        layout.addWidget(self.defense_info)
        layout.addWidget(simulate_btn)
        layout.addWidget(QLabel("防御效果:"))
        layout.addWidget(self.defense_result)
        layout.addWidget(QLabel("统计信息:"))
        layout.addWidget(self.stats_text)
        
        self.setLayout(layout)
        self.attack_history = []
        self.update_defense_info()
        
    def toggle_defense_selection(self, mode):
        """切换防御措施选择模式"""
        for checkbox in self.defense_checkboxes:
            checkbox.setVisible(mode == "手动选择")
            
    def update_defense_info(self):
        """更新防御策略信息"""
        attack_type = self.attack_type.currentText()
        defense_strategies = {
            "DDoS攻击": {
                "description": "分布式拒绝服务攻击，通过大量请求使目标系统无法正常服务",
                "measures": [
                    "流量清洗 - 使用WAF进行流量过滤，实施IP黑名单，启用CDN服务",
                    "负载均衡 - 多节点部署，动态扩缩容，流量分发",
                    "监控告警 - 实时流量监控，异常流量检测，自动告警机制"
                ],
                "risk_levels": {
                    "低强度": "每秒1000请求以下",
                    "中强度": "每秒1000-5000请求",
                    "高强度": "每秒5000请求以上"
                }
            },
            "中间人攻击": {
                "description": "攻击者在通信双方之间截获、篡改或伪造通信内容",
                "measures": [
                    "加密通信 - 使用TLS/SSL，实施端到端加密，证书验证",
                    "身份认证 - 双向认证，数字签名，证书链验证",
                    "会话管理 - 会话超时，会话ID随机化，防止会话劫持"
                ],
                "risk_levels": {
                    "低强度": "单次通信拦截",
                    "中强度": "持续通信监控",
                    "高强度": "实时通信篡改"
                }
            },
            "重放攻击": {
                "description": "攻击者截获合法通信后，在后续时间重放该通信",
                "measures": [
                    "时间戳验证 - 请求时间戳检查，时间窗口限制，时钟同步",
                    "随机数机制 - 使用Nonce，一次性令牌，请求签名",
                    "序列号控制 - 请求序列号，序列号验证，防止重放"
                ],
                "risk_levels": {
                    "低强度": "单次重放",
                    "中强度": "多次重放",
                    "高强度": "持续重放"
                }
            },
            "SQL注入": {
                "description": "通过构造特殊SQL语句，获取或修改数据库信息",
                "measures": [
                    "参数化查询 - 使用预处理语句，参数绑定，类型检查",
                    "输入验证 - 白名单过滤，特殊字符转义，长度限制",
                    "权限控制 - 最小权限原则，数据库用户隔离，敏感操作审计"
                ],
                "risk_levels": {
                    "低强度": "简单查询注入",
                    "中强度": "复杂查询注入",
                    "高强度": "多语句注入"
                }
            },
            "XSS攻击": {
                "description": "在网页中注入恶意脚本，获取用户信息或执行恶意操作",
                "measures": [
                    "输入过滤 - HTML转义，JavaScript转义，特殊字符处理",
                    "输出编码 - 上下文相关编码，内容安全策略，XSS过滤器",
                    "安全配置 - 设置HttpOnly，启用CSP，禁用内联脚本"
                ],
                "risk_levels": {
                    "低强度": "反射型XSS",
                    "中强度": "存储型XSS",
                    "高强度": "DOM型XSS"
                }
            },
            "权限提升": {
                "description": "利用系统漏洞或配置错误，获取更高权限",
                "measures": [
                    "访问控制 - 基于角色的访问控制，最小权限原则，权限分离",
                    "身份验证 - 多因素认证，会话管理，登录限制",
                    "审计监控 - 操作日志记录，异常行为检测，定期权限审查"
                ],
                "risk_levels": {
                    "低强度": "单用户权限提升",
                    "中强度": "多用户权限提升",
                    "高强度": "系统级权限提升"
                }
            }
        }
        
        strategy = defense_strategies.get(attack_type, {})
        if strategy:
            info = f"""
攻击类型: {attack_type}
攻击描述: {strategy['description']}

风险等级:
{strategy['risk_levels']['低强度']}
{strategy['risk_levels']['中强度']}
{strategy['risk_levels']['高强度']}

防御措施:
1. {strategy['measures'][0]}
2. {strategy['measures'][1]}
3. {strategy['measures'][2]}
"""
            self.defense_info.setPlainText(info)
            
            # 更新防御措施复选框标签
            for i, measure in enumerate(strategy['measures']):
                self.defense_checkboxes[i].setText(measure.split(' - ')[0])
        
    def simulate_attack(self):
        """模拟攻击并展示防御效果"""
        attack_type = self.attack_type.currentText()
        attack_strength = self.attack_params.currentText()
        current_time = datetime.now()
        
        # 获取防御措施
        if self.defense_measures.currentText() == "自动选择":
            measures = random.sample(self.get_defense_measures(attack_type), 2)
        else:
            measures = [cb.text() for cb in self.defense_checkboxes if cb.isChecked()]
            if not measures:
                QMessageBox.warning(self, "警告", "请至少选择一个防御措施")
                return
        
        # 根据攻击强度调整防御效果
        success_rates = {
            "低强度": 0.9,  # 90%成功率
            "中强度": 0.7,  # 70%成功率
            "高强度": 0.5   # 50%成功率
        }
        
        for measure in measures:
            # 计算防御结果
            success_rate = success_rates[attack_strength]
            result = random.choices(
                ["成功", "失败", "警告"],
                weights=[success_rate, (1-success_rate)*0.7, (1-success_rate)*0.3]
            )[0]
            
            # 添加到历史记录
            self.attack_history.append({
                "time": current_time,
                "attack_type": attack_type,
                "attack_strength": attack_strength,
                "measure": measure,
                "result": result
            })
            
            # 更新表格
            row = self.defense_result.rowCount()
            self.defense_result.insertRow(row)
            self.defense_result.setItem(row, 0, QTableWidgetItem(current_time.strftime("%Y-%m-%d %H:%M:%S")))
            self.defense_result.setItem(row, 1, QTableWidgetItem(attack_type))
            self.defense_result.setItem(row, 2, QTableWidgetItem(attack_strength))
            self.defense_result.setItem(row, 3, QTableWidgetItem(measure))
            
            # 设置结果颜色
            result_item = QTableWidgetItem(result)
            if result == "成功":
                result_item.setForeground(Qt.green)
            elif result == "失败":
                result_item.setForeground(Qt.red)
            else:
                result_item.setForeground(Qt.orange)
            self.defense_result.setItem(row, 4, result_item)
            
        # 更新统计信息
        self.update_stats()
        
    def get_defense_measures(self, attack_type):
        """获取指定攻击类型的防御措施"""
        measures = {
            "DDoS攻击": ["流量清洗", "负载均衡", "监控告警"],
            "中间人攻击": ["加密通信", "身份认证", "会话管理"],
            "重放攻击": ["时间戳验证", "随机数机制", "序列号控制"],
            "SQL注入": ["参数化查询", "输入验证", "权限控制"],
            "XSS攻击": ["输入过滤", "输出编码", "安全配置"],
            "权限提升": ["访问控制", "身份验证", "审计监控"]
        }
        return measures.get(attack_type, [])
        
    def update_stats(self):
        """更新统计信息"""
        if not self.attack_history:
            return
            
        total = len(self.attack_history)
        success = sum(1 for h in self.attack_history if h["result"] == "成功")
        failed = sum(1 for h in self.attack_history if h["result"] == "失败")
        warning = sum(1 for h in self.attack_history if h["result"] == "警告")
        
        # 按攻击类型和强度统计
        attack_stats = {}
        for h in self.attack_history:
            key = (h["attack_type"], h["attack_strength"])
            if key not in attack_stats:
                attack_stats[key] = {"total": 0, "success": 0}
            attack_stats[key]["total"] += 1
            if h["result"] == "成功":
                attack_stats[key]["success"] += 1
        
        stats = f"""
防御统计:
总防御次数: {total}
成功防御: {success} ({success/total*100:.1f}%)
防御失败: {failed} ({failed/total*100:.1f}%)
防御警告: {warning} ({warning/total*100:.1f}%)

各攻击类型防御效果:
"""
        for (attack_type, strength), data in attack_stats.items():
            success_rate = data["success"] / data["total"] * 100
            stats += f"{attack_type} ({strength}): {data['success']}/{data['total']} ({success_rate:.1f}%)\n"
            
        self.stats_text.setPlainText(stats)

# ----------------- 主窗口集成 -----------------
class MainWindow(QMainWindow):
    def __init__(self, user_role="admin", username="admin"):
        super().__init__()
        self.setWindowTitle("智能车联网统一多域标识认证安全管理系统 v1.0")
        self.setWindowIcon(QIcon("resources/sd.png"))  # 添加图标设置
        self.user_role = user_role
        self.username = username
        self._init_ui()
        self._setup_permissions()
        self._setup_status_bar()
        

    def _init_ui(self):
        self.resize(1200, 800)
        
        # 主布局
        main_widget = QWidget()
        main_layout = QHBoxLayout()
        
        # 左侧导航
        self.nav_list = QListWidget()
        self.nav_list.addItems(["标识管理", "跨域认证", "密钥管理", "安全通信", "审计模块", "零信任策略", "模拟数据生成", "数据验证", "安全防御"])
        self.nav_list.currentRowChanged.connect(self.switch_page)
        
        # 右侧内容
        self.stack = QStackedWidget()
        self.stack.addWidget(IdentifierUI())
        self.stack.addWidget(AuthUI())
        self.stack.addWidget(KeyManagerUI())
        self.stack.addWidget(SecureCommUI())
        self.stack.addWidget(ZeroTrustPolicyUI())
        self.stack.addWidget(DataGeneratorUI())
        self.stack.addWidget(DataValidatorUI())
        self.stack.addWidget(SecurityDefenseUI())
        
        # 组合布局
        main_layout.addWidget(self.nav_list, stretch=1)
        main_layout.addWidget(self.stack, stretch=4)
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        
        # 样式优化
        self.nav_list.setStyleSheet("""
            QListWidget {
                font-size: 16px;
                padding: 15px;
            }
            QListWidget::item {
                height: 40px;
            }
        """)

    def _setup_permissions(self):
        """根据登录角色设置权限"""
        if self.user_role == "车载终端用户":
            # 禁用密钥管理和审计模块
            self.nav_list.item(2).setFlags(Qt.NoItemFlags)  # 禁用密钥管理
            self.nav_list.item(4).setFlags(Qt.NoItemFlags)  # 禁用审计模块
        elif self.user_role == "系统审计员":
            # 仅允许访问审计模块
            for i in range(self.nav_list.count()):
                if i != 4:  # 除了审计模块
                    self.nav_list.item(i).setFlags(Qt.NoItemFlags)
    
    def _setup_status_bar(self):
        """设置状态栏显示用户信息"""
        status_bar = self.statusBar()
        status_bar.setStyleSheet("""
            QStatusBar {
                background-color: #f0f0f0;
                color: #333333;
                font-size: 14px;
                padding: 5px;
            }
        """)
        
        # 创建用户信息标签
        user_info = QLabel(f"当前用户: {self.username} | 角色: {self.user_role}")
        user_info.setStyleSheet("""
            QLabel {
                padding: 5px;
                border-radius: 3px;
                background-color: #e0e0e0;
            }
        """)
        
        # 将标签添加到状态栏
        status_bar.addPermanentWidget(user_info)

    def switch_page(self, index):
        self.stack.setCurrentIndex(index)

# ----------------- 程序入口 -----------------
if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


